package org.whale.bha.handler;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.whale.bha.util.XMLConverUtil;

public class ResponseHandlerTool {
	public static final String DEFAULT_CHARSET = "UTF-8";

	/**
	 * 返回实体类handler
	 * @param clazz
	 * @return
	 */
	public static <T> ResponseHandler<T> createResponseHandler(final Class<T> clazz){

		ResponseHandler<T> responseHandler = new ResponseHandler<T>() {

		    public T handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
		        int status = response.getStatusLine().getStatusCode();
		        if (status >= 200 && status < 300) {
		            HttpEntity entity = response.getEntity();
		            String str= entity != null ? EntityUtils.toString(entity,DEFAULT_CHARSET) : null;
		            return XMLConverUtil.convertToObject(clazz,str);
		        } else {
		            throw new ClientProtocolException("Unexpected response status: " + status);
		        }
		    }

		};
		return responseHandler;
	}
	
    
    /**
     * <p>默认的处理返回值为String的ResponseHandler</p>
     */
    public static ResponseHandler<String> createStringResponseHandler() {
    	ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

		    public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
		        int status = response.getStatusLine().getStatusCode();
		        if (status >= 200 && status < 300) {
		            HttpEntity entity = response.getEntity();
		            return entity != null ? EntityUtils.toString(entity,DEFAULT_CHARSET) : null;
		        } else {
		            throw new ClientProtocolException("Unexpected response status: " + status);
		        }
		    }
		};
		return responseHandler;
	}
}
